package com.song.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Listener extends Thread{

	private ServerSocket socket;
	
	private Server server;
	
	
	
	public Listener(Server server) {
		super();
		this.server = server;
	}



	@Override
	public void run() {
		
		try {
			System.out.println("启动服务器中，打开端口" + server.getPort()); 
			socket  = new ServerSocket(server.getPort());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		while(server.isRunning())
		{
			
			try {
				Socket client = socket.accept();
				ObjectInputStream ois = new ObjectInputStream(client.getInputStream());
				
				Invocation invo =(Invocation)ois.readObject();
				server.call(invo);
				
				ObjectOutput oos = new ObjectOutputStream(client.getOutputStream());
				oos.writeObject(invo);
				oos.flush();
				oos.close();
				ois.close();
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		
		try {
			if(socket!= null && !socket.isClosed())
			{
					socket.close();	
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}







	
	
	


}
